package com.xiaoxin.dubbo.api;

import cn.hutool.core.date.DateUtil;
import com.xiaoxin.model.mongo.Visitors;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @author xiaoxiaode
 * @date 2021-09-10-19:31
 **/
@DubboService
public class VisitorsApiImpl implements VisitorsApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Visitors visitors) {
        // 保存访客记录,对于同一个用户,一天之内只能保存一次访客数据
        //查询访客用户在今天是否已经记录过，如果已经记录过，不再记录
        String today = DateUtil.today();
        Long minDate = DateUtil.parseDateTime(today + " 00:00:00").getTime();
        Long maxDate = DateUtil.parseDateTime(today + " 23:59:59").getTime();
        Query query = Query.query(Criteria.where("userId").is(visitors.getUserId())
                .and("visitorUserId").is(visitors.getVisitorUserId())
                // .and("visitDate").is(visitors.getVisitDate()));
                .andOperator(Criteria.where("date").gte(minDate)
                        , Criteria.where("date").lte(maxDate)));
        if (!mongoTemplate.exists(query, Visitors.class)) {
            mongoTemplate.save(visitors);
        }

    }

    @Override
    public List<Visitors> find(Long date, Long userId) {
        Criteria criteria = Criteria.where("userId").is(userId);
        if (date != null) {
            criteria.and("date").gt(date);
        }
        Query query = Query.query(criteria).limit(5).with(Sort.by(Sort.Order.desc("date")));
        return mongoTemplate.find(query, Visitors.class);
    }

    @Override
    public Visitors findOne(Long userId, Long visitorUserId) {
        Criteria criteria = Criteria.where("userId").is(userId).and("visitorUserId").is(visitorUserId);
        Query query=Query.query(criteria);
        return mongoTemplate.findOne(query, Visitors.class);
    }

}
